/*
 * @Date: 2023-12-26 13:35:46
 * @LastEditors: lyx
 * @LastEditTime: 2024-03-08 09:07:01
 * @FilePath: \taro-template3\src\lib\auth\index.ts
 * @Description: 微信授权认证逻辑
 */
import { ApiGetUserInfo } from "@/api/auth";
import { navigateTo } from "@tarojs/taro";
import Taro from "@tarojs/taro";
import { store } from "@/store/index";
import { clear, setAuth, setUserInfo } from "@/store/reducers/user";

/**
 * 检查令牌是否有效
 * @returns {boolean} true 有效， false 无效
 */
export const hasAuth = () => {
  const { user } = store.getState();
  const { token } = user || {};
  console.log("hasAuth user", user);
  if (!token) {
    return false;
  }
  return true;

  // let expiryTime = 0;
  // const nowTime = Date.now();
  // let authTime = auth.exipreTime;
  // // TODO: 判断是否过期这一步要不要？
  // if (authTime) {
  //   if (typeof authTime === "string") {
  //     authTime = auth.exipreTime.replace(/-/g, "/");
  //   }
  //   const exp = new Date(authTime).getTime();
  //   expiryTime = exp;
  // }
  // return expiryTime - nowTime > 300;
};

/**
 * 如果没有令牌先进行登录
 * @param {}
 * @return
 */
export const checkAuth = (
  callback = () => {},
  options?: { backurl?: string; isSwitchTab?: boolean }
) => {
  const { backurl = "", isSwitchTab } = options || {};
  if (hasAuth()) {
    callback();
  } else {
    navigateTo({
      url:
        "/sub_common/pages/auth/index" +
        `?backurl=${encodeURIComponent(backurl)}&isSwitchTab=${
          isSwitchTab ? "1" : ""
        }`,
    });
  }
};

/**
 * 退出登陆
 * @param {}
 * @return
 */
export const loginout = () => {
  store.dispatch(clear());
  navigateTo({
    url: "/sub_common/pages/auth/index",
  });
};

/**
 * 获取用户信息
 * @param {}
 * @return
 */
export const getUserInfo = ({ token, exipreTime, callback }: any = {}) => {
  if (!token) {
    const { user } = store.getState();
    const { auth } = user || {};
    token = auth.token;
    exipreTime = auth.exipreTime;
  } else {
    store.dispatch(setAuth({ token, exipreTime }));
  }
  let userInfo = {};
  ApiGetUserInfo({}).then((res: any) => {
    console.log("ApiGetUserInfo res", res);
    if (res.isSuccess) {
      userInfo = res.content;
      store.dispatch(setUserInfo(userInfo));
      if (callback) {
        callback();
        return;
      }
    } else {
      Taro.showToast({
        title: res.msg,
        icon: "none",
        duration: 2000,
      });
      return;
    }
  });
};
